use log;
use std::sync::Arc;
use sip_auth::{DigestAuthenticator, DigestCredentials, DigestUser};
use sip_core::{transport::udp::Udp, transport::tcp::TcpConnector, Endpoint};
use sip_ua::{dialog::DialogLayer, invite::InviteLayer, RegistrarConfig, Registration};
use crate::models::state::{GLOBAL_STATE, ConnectionConfig, ConnectionResult};
use crate::utils::network::get_local_ip_for_target;

pub async fn initialize_sip_endpoint(target_ip: &str) -> Result<(), String> {
    log::info!("初始化全局SIP端点，目标IP: {}", target_ip);
    let mut builder = Endpoint::builder();
    let local_ip = get_local_ip_for_target(target_ip)?;
    log::info!("使用本地IP地址: {}", local_ip);
    let udp_ports = [format!("{}:5060", local_ip), format!("{}:5061", local_ip), format!("{}:5062", local_ip), format!("{}:5063", local_ip)];
    let mut udp_bound = false;
    for port in &udp_ports {
        match Udp::spawn(&mut builder, port).await { Ok(_) => { log::info!("全局UDP传输绑定成功: {}", port); udp_bound = true; break; }, Err(e) => { log::warn!("UDP端口 {} 绑定失败: {}, 尝试下一个端口", port, e); continue; } }
    }
    if !udp_bound { return Err("所有UDP端口都绑定失败".to_string()); }
    builder.add_transport_factory(Arc::new(TcpConnector::new()));
    builder.add_layer(DialogLayer::default());
    builder.add_layer(InviteLayer::default());
    let endpoint = builder.build();
    log::info!("全局SIP端点构建完成");
    { let mut state_guard = GLOBAL_STATE.lock().await; state_guard.global_endpoint = Some(endpoint); state_guard.is_initialized = true; }
    Ok(())
}

pub async fn connect_sip(config: ConnectionConfig) -> Result<ConnectionResult, String> {
    log::info!("开始SIP连接: 用户={}, 域={}, 传输={}", config.username, config.domain, config.transport);
    let domain_parts: Vec<&str> = config.domain.split(':').collect();
    let (host, _port) = if domain_parts.len() == 2 { (domain_parts[0], domain_parts[1]) } else { (domain_parts[0], "5060") };
    { let state_guard = GLOBAL_STATE.lock().await; if !state_guard.is_initialized { log::info!("首次连接，初始化SIP端点"); drop(state_guard); initialize_sip_endpoint(host).await?; } }
    { let mut state_guard = GLOBAL_STATE.lock().await; if state_guard.registration.is_some() { log::info!("检测到现有连接，先断开"); if let Some(registration) = state_guard.registration.take() { drop(registration); log::info!("现有SIP注册已取消"); } } }
    let sip_uri = if config.transport == "TCP" { format!("sip:{};transport=TCP", host) } else { format!("sip:{}", host) };
    log::info!("SIP URI: {}", sip_uri);
    let endpoint = { let state_guard = GLOBAL_STATE.lock().await; state_guard.global_endpoint.clone().ok_or("全局SIP端点未初始化，请重启应用程序")? };
    let mut credentials = DigestCredentials::new();
    credentials.add_for_realm(host, DigestUser::new(config.username.clone(), config.password.as_bytes().to_vec()));
    let registration = Registration::register(endpoint, RegistrarConfig::new(config.username.clone(), sip_uri.parse().map_err(|e| format!("SIP URI解析失败: {}", e))?), DigestAuthenticator::new(credentials.clone())).await.map_err(|e| format!("SIP注册失败: {}", e))?;
    log::info!("SIP注册成功: 用户={}", config.username);
    { let mut state_guard = GLOBAL_STATE.lock().await; state_guard.registration = Some(Arc::new(registration)); state_guard.last_credentials = Some(credentials); state_guard.last_host = Some(host.to_string()); }
    Ok(ConnectionResult { success: true, message: format!("成功连接到SIP服务器: {}", config.domain) })
}

pub async fn disconnect_sip() -> Result<ConnectionResult, String> {
    log::info!("断开SIP连接");
    { let mut state_guard = GLOBAL_STATE.lock().await; if let Some(registration) = state_guard.registration.take() { drop(registration); log::info!("SIP注册已取消"); } }
    Ok(ConnectionResult { success: true, message: "SIP连接已断开".to_string() })
}

pub async fn get_connection_status() -> Result<ConnectionResult, String> {
    let state_guard = GLOBAL_STATE.lock().await; let is_connected = state_guard.registration.is_some();
    Ok(ConnectionResult { success: is_connected, message: if is_connected { "已连接到SIP服务器".to_string() } else { "未连接到SIP服务器".to_string() } })
}



